package concurrent.printAB;

import java.util.concurrent.CountDownLatch;

/**
 * @author why
 * @data 2021/8/4
 */
public class PrintABCountDownLatch {
    private static final int MAX_PRINT_NUM = 100;
    private static volatile int count = 0;

    public static void printAB() {
        // 声明CountDownLatch
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(() -> {
            while (count < MAX_PRINT_NUM) {
                if (count % 2 == 0) {
                    System.out.println("num:" + count);
                    count++;
                }
            }
            // 偶数线程执行完则计数器减一
            countDownLatch.countDown();
        }).start();

        new Thread(() -> {
            while (count < MAX_PRINT_NUM) {
                if (count % 2 == 1) {
                    System.out.println("num:" + count);
                    count++;
                }
            }
            // 奇数线程执行完则计数器减一
            countDownLatch.countDown();
        }).start();

        try {
            countDownLatch.await();
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        printAB();
    }
}
